package cn.zc.spring_minio1.controller;


import cn.zc.spring_minio1.entity.UserInfo;
import cn.zc.spring_minio1.result.R;
import cn.zc.spring_minio1.service.UserInfoService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MinioClient minioClient;
    @GetMapping(value = "/api/users")
    public R users(){
        List<UserInfo> list = userInfoService.list();
        return R.success(list);
    }
    @PostMapping(value = "/api/user/image")
    public R image(MultipartFile file) throws Exception {
        //1234.jpg
        String subfix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
//        String object = id+subfix;
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .bucket("myfile")
                .object(subfix) //.png  .jpg
                .stream(file.getInputStream(), file.getSize(), -1)
                .build()
        );
        System.out.println(objectWriteResponse);


        return R.success();
    }

    @PostMapping(value = "/api/user/contract")
    public R contract(MultipartFile file, @RequestParam(value = "id") Integer id) throws Exception {
        //1234.jpg
        String subfix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        String object = id+subfix;
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .bucket("myfile")
                .object(object)
                .stream(file.getInputStream(), file.getSize(), -1)
                .build()
        );
        System.out.println(objectWriteResponse);

        return R.success();
    }
}
